import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: uni.getStorageSync('token') || '',
    userInfo: uni.getStorageSync('userInfo') || null,
    permissions: uni.getStorageSync('permissions') || []
  }),

  getters: {
    isLoggedIn: (state) => !!state.token,
    userName: (state) => state.userInfo?.username || '',
    hasPermission: (state) => (permission) => {
      return state.permissions.includes(permission)
    }
  },

  actions: {
    async login(credentials) {
      try {
        // 模拟API请求
        // const response = await uni.request({
        //   url: '/api/login',
        //   method: 'POST',
        //   data: credentials
        // })

        // 模拟登录成功响应
        const response = {
          data: {
            success: true,
            data: {
              token: 'mock_token_' + Date.now(),
              userInfo: {
                id: 1,
                username: credentials.username,
                nickname: '测试用户',
                avatar: '/static/images/avatar.png'
              },
              permissions: ['device:view']
            }
          }
        }

        if (response.data.success) {
          const { token, userInfo, permissions } = response.data.data
          
          // 保存到store
          this.token = token
          this.userInfo = userInfo
          this.permissions = permissions

          // 保存到本地存储
          uni.setStorageSync('token', token)
          uni.setStorageSync('userInfo', userInfo)
          uni.setStorageSync('permissions', permissions)

          return {
            success: true
          }
        } else {
          return {
            success: false,
            message: response.data.message || '登录失败'
          }
        }
      } catch (error) {
        console.error('登录失败:', error)
        return {
          success: false,
          message: '网络错误，请稍后重试'
        }
      }
    },

    logout() {
      // 清除store
      this.token = ''
      this.userInfo = null
      this.permissions = []

      // 清除本地存储
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('permissions')
      uni.removeStorageSync('remembered_username')
      uni.removeStorageSync('remembered_password')
    },

    async updateUserInfo(userInfo) {
      try {
        // 模拟API请求
        // await uni.request({
        //   url: '/api/user/profile',
        //   method: 'PUT',
        //   data: userInfo
        // })

        this.userInfo = { ...this.userInfo, ...userInfo }
        uni.setStorageSync('userInfo', this.userInfo)

        return {
          success: true
        }
      } catch (error) {
        console.error('更新用户信息失败:', error)
        return {
          success: false,
          message: '更新用户信息失败'
        }
      }
    },

    async refreshToken() {
      try {
        // 模拟API请求
        // const response = await uni.request({
        //   url: '/api/refresh-token',
        //   method: 'POST',
        //   data: {
        //     token: this.token
        //   }
        // })

        const response = {
          data: {
            success: true,
            data: {
              token: 'mock_token_' + Date.now()
            }
          }
        }

        if (response.data.success) {
          const { token } = response.data.data
          this.token = token
          uni.setStorageSync('token', token)
          return true
        }
        return false
      } catch (error) {
        console.error('刷新token失败:', error)
        return false
      }
    }
  }
})